package com.isunland.managesystem.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CompoundButton;
import butterknife.BindView;
import butterknife.ButterKnife;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseFragment;
import com.isunland.managesystem.base.BaseOriginal;
import com.isunland.managesystem.base.BaseTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.SimpleReturnResponse;
import com.isunland.managesystem.common.SimpleToastResponse;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.BaseParams;
import com.isunland.managesystem.entity.DDictionary;
import com.isunland.managesystem.entity.DDictionaryListOriginal;
import com.isunland.managesystem.entity.DataStatus;
import com.isunland.managesystem.entity.RSealsUseApp;
import com.isunland.managesystem.entity.SealUseDetailParams;
import com.isunland.managesystem.entity.SimpleNetworkCallBackDialogParams;
import com.isunland.managesystem.utils.FileUtil;
import com.isunland.managesystem.utils.MenuUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyStringUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.MyViewUtil;
import com.isunland.managesystem.utils.ParamsNotEmpty;
import com.isunland.managesystem.utils.ToastUtil;
import com.isunland.managesystem.widget.CheckLineView;
import com.isunland.managesystem.widget.MultiLinesView;
import com.isunland.managesystem.widget.SingleLineView;
import java.util.ArrayList;
import java.util.Date;
import org.json.JSONException;

/**
 * 对象功能:
 * 开发公司: 北京信普达系统工程有限公司
 * 开发人员: wangyanan
 * 创建时间: 2017/6/23 19:12
 */

public class SealUseDetailFragment extends BaseFragment {
  private static final int REQUEST_CHOOSE_FILE = 1;
  private static final int MENU_ITEM_CONFIRM = 2;
  private static final int MENU_ITEM_ALTER = 3;
  private static final int MENU_ITEM_DELETE = 4;
  private static final int MENU_ITEM_RUN = 5;
  private static final int MENU_ITEM_STOP = 6;
  private static final int REQUEST_ALTER = 7;
  @BindView(R.id.slv_applyNo) SingleLineView slvApplyNo;
  @BindView(R.id.slv_regStaffName2) SingleLineView slvRegStaffName2;
  @BindView(R.id.slv_applydeptName) SingleLineView slvApplydeptName;
  @BindView(R.id.slv_applydeptDate) SingleLineView slvApplydeptDate;
  @BindView(R.id.slv_sealsType) SingleLineView slvSealsType;
  @BindView(R.id.slv_applyText) MultiLinesView slvApplyText;
  @BindView(R.id.clv_isCarryOutName) CheckLineView clvIsCarryOutName;
  @BindView(R.id.slv_useName) SingleLineView slvUseName;
  @BindView(R.id.slv_docBlob) SingleLineView slvDocBlob;
  @BindView(R.id.slv_regDate) SingleLineView slvRegDate;
  @BindView(R.id.slv_dataStatus) SingleLineView slvDataStatusName;
  @BindView(R.id.slv_agent) SingleLineView slvAgent;
  @BindView(R.id.slv_actUseDays) SingleLineView slvActUseDays;
  //optimize
  @BindView(R.id.slv_actBackDays) SingleLineView slvActBackDays;
  @BindView(R.id.slv_remark) SingleLineView slvRemark;
  private RSealsUseApp mItem;
  private SealUseDetailParams mParams;

  @Override public void initData() {
    super.initData();
    mParams = !(mBaseParams instanceof SealUseDetailParams) ? new SealUseDetailParams()
        : (SealUseDetailParams) mBaseParams;
    mItem = mParams.getItem() == null ? new RSealsUseApp() : mParams.getItem();
    //添加的时候获取默认的网络数据.使用途径的第一条数据.
    if (SealUseDetailParams.TYPE_ADD == mParams.getType()) {
      volleyPostUseName();
    }
  }

  private void volleyPostUseName() {
    mActivity.volleyPost(ApiConst.getAbsoluteUrl(ApiConst.URL_QUERY_LIST_DICTIONARY),
        new ParamsNotEmpty().put("memberCode", mCurrentUser.getMemberCode())
            .put("dictFlag", "oaSealsUse")
            .getParams(), new VolleyResponse() {
          @Override public void onVolleyError(VolleyError arg0) {

          }

          @Override public void onVolleyResponse(String json) throws JSONException {
            BaseOriginal<DDictionary> result =
                new Gson().fromJson(json, new TypeToken<BaseOriginal<DDictionary>>() {
                }.getType());
            DDictionary item = result.getRows().get(0);
            mItem.setUseCode(item.getRecordCode());
            mItem.setUseName(item.getRecordText());
            slvUseName.setTextContent(item.getRecordText());
          }

          @Override public boolean ifToastError() {
            return false;
          }
        });
  }

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_seal_use_detail, container, false);
    ButterKnife.bind(this, view);
    return view;
  }

  @Override public void initView(View view, Bundle savedInstanceState) {
    super.initView(view, savedInstanceState);
    setTitleCustom(mParams.getTitle());

    slvApplydeptDate.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        showDialog(BaseTimeDialogFragment.newInstance(mItem.getApplydeptDate())
            .setCallBack(new BaseTimeDialogFragment.CallBack() {
              @Override public void select(Date date) {
                if (date == null) return;
                mItem.setApplydeptDate(date);
                slvApplydeptDate.setTextContent(MyDateUtil.format(mItem.getApplydeptDate()));
              }
            }), 0);
      }
    });
    slvActBackDays.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        showDialog(BaseTimeDialogFragment.newInstance(mItem.getActBackDays())
            .setCallBack(new BaseTimeDialogFragment.CallBack() {
              @Override public void select(Date date) {
                if (date == null) return;
                mItem.setActBackDays(date);
                slvActBackDays.setTextContent(MyDateUtil.format(mItem.getActBackDays()));
              }
            }), 0);
      }
    });
    slvSealsType.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        SimpleNetworkCallBackDialogParams params = new SimpleNetworkCallBackDialogParams();
        params.setUrl(ApiConst.getAbsoluteUrl(ApiConst.URL_QUERY_LIST_DICTIONARY));
        params.setParameters(new ParamsNotEmpty().put("memberCode", mCurrentUser.getMemberCode())
            .put("dictFlag", "oaSealsType")
            .getParams());
        params.setShowField("recordText");
        params.setClassOriginal(DDictionaryListOriginal.class);
        showDialog(BaseDialogFragment.newInstance(params,
            new SimpleNetworkMultiCallBackDialogFragment<DDictionary>().setCallBack(
                new SimpleNetworkMultiCallBackDialogFragment.CallBack<DDictionary>() {

                  @Override public void select(ArrayList<DDictionary> list) {
                    if (list == null || list.size() == 0) return;
                    mItem.setSealsType(
                        MyStringUtil.joinStr(list, "recordText", MyStringUtil.COMMA));
                    mItem.setSealsTypeCode(
                        MyStringUtil.joinStr(list, "recordCode", MyStringUtil.COMMA));
                    slvSealsType.setTextContent(mItem.getSealsType());
                  }
                })), 0);
      }
    });

    slvUseName.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        SimpleNetworkCallBackDialogParams params = new SimpleNetworkCallBackDialogParams();
        params.setUrl(ApiConst.getAbsoluteUrl(ApiConst.URL_QUERY_LIST_DICTIONARY));
        params.setParameters(new ParamsNotEmpty().put("memberCode", mCurrentUser.getMemberCode())
            .put("dictFlag", "oaSealsUse")
            .getParams());
        params.setShowField("recordText");
        params.setClassOriginal(DDictionaryListOriginal.class);
        showDialog(BaseDialogFragment.newInstance(params,
            new SimpleNetworkCallBackDialogFragment<DDictionary>().setCallBack(
                new SimpleNetworkCallBackDialogFragment.CallBack<DDictionary>() {

                  @Override public void select(DDictionary base) {
                    if (base == null) return;
                    mItem.setUseName(base.getRecordText());
                    mItem.setUseCode(base.getRecordCode());
                    slvUseName.setTextContent(base.getRecordText());
                  }
                })), 0);
      }
    });

    clvIsCarryOutName.getCbCheck()
        .setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
          @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            //由于详情的时候禁用checkbox不好看,只能在这里做判断,恢复原来的选项.
            if (SealUseDetailParams.TYPE_DETAIL == mParams.getType()) {
              clvIsCarryOutName.getCbCheck().setChecked(mItem.isCarryOut());
              return;
            }
            mItem.setIsCarryOut(
                isChecked ? RSealsUseApp.CARRY_OUT_TRUE : RSealsUseApp.CARRY_OUT_FALSE);
          }
        });

    slvDocBlob.getTvContent().setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        if (BaseParams.TYPE_DETAIL == mParams.getType()) {
          if (MyStringUtil.isEmpty(mItem.getDocPath())) return;
          showDialog(ExtraDownLoadDialogFragment.newInstance("", mItem.getDocPath()), 0);
        } else {
          MyUtils.chooseFile(SealUseDetailFragment.this, REQUEST_CHOOSE_FILE);
        }
      }
    });

    //详情的时候禁用选择框
    if (mBaseParams.getType() == BaseParams.TYPE_DETAIL) {
      MyViewUtil.setEnableAll(false, slvApplydeptDate.getTvContent(), slvApplyText.getTvContent(),
          slvSealsType.getTvContent(), slvDataStatusName.getTvContent(), slvRegDate.getTvContent(),
          slvRemark.getTvContent(), slvUseName.getTvContent());
    }
    //流程填写实际归还时间
    if (mParams.isEditBackTime()) slvActBackDays.setInputEnabled(true);
    //添加,修改.
    //if ((mBaseParams.getType() == BaseParams.TYPE_ADD) || (mBaseParams.getType()
    //    == BaseParams.TYPE_EDIT)) {
    //  MyViewUtil.setVisibilityAll(View.GONE, slvRemark);
    //}

    bindData(mItem);
    volleyPostInit(mItem.getId());
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    if (item == null) return false;
    if (MENU_ITEM_CONFIRM == item.getItemId()) {
      volleyPostSave(new SimpleReturnResponse(mActivity));
    }
    if (MENU_ITEM_RUN == item.getItemId()) {
      volleyPostRun(mItem.getId());
    }
    if (MENU_ITEM_STOP == item.getItemId()) {
      volleyPostStop(mItem.getId(), mItem.getRunId());
    }
    if (MENU_ITEM_ALTER == item.getItemId()) {
      if (!(MyStringUtil.equals(DataStatus.NEW, mItem.getDataStatus()) || MyStringUtil.equals(
          DataStatus.ABORT, mItem.getDataStatus()))) {
        ToastUtil.show(R.string.draftOrAbort);
        return false;
      }
      SealUseDetailParams params = new SealUseDetailParams();
      params.setType(BaseParams.TYPE_EDIT);
      params.setTitle(MyStringUtil.connect(R.string.sealUse, R.string.alter));
      params.setItem(mItem);
      params.setShowMenuConfirm(true);
      params.setShowMenuRun(true);
      SealUseDetailActivity.newInstance(this, SealUseDetailActivity.class, params, REQUEST_ALTER);
    }
    if (MENU_ITEM_DELETE == item.getItemId()) {
      volleyPostDelete(mItem.getId());
    }

    return super.onOptionsItemSelected(item);
  }

  private void volleyPostRun(final String id) {
    if (TextUtils.isEmpty(id)) return;
    if (!(MyStringUtil.equals(DataStatus.NEW, mItem.getDataStatus()) || MyStringUtil.equals(
        DataStatus.ABORT, mItem.getDataStatus()))) {
      ToastUtil.show(R.string.draftOrAbort);
      return;
    }
    volleyPostSave(new SimpleToastResponse() {
      @Override public void onVolleyResponse(String json) throws JSONException {
        super.onVolleyResponse(json);
        if (!isSuccess()) return;
        String url = ApiConst.getAbsoluteUrl(ApiConst.URL_UPDATE_RUN_SEALUSE);
        ParamsNotEmpty params = new ParamsNotEmpty();
        params.put("id", id);
        MyUtils.showDialogLoading(getActivity());
        mActivity.volleyPost(url, params.getParams(), new SimpleReturnResponse(mActivity));
      }
    });
  }

  private void volleyPostStop(String id, long runId) {
    if (TextUtils.isEmpty(id) || runId == 0) return;
    if (!MyStringUtil.equals(DataStatus.WAIT_CHECK, mItem.getDataStatus())) {
      ToastUtil.show(R.string.notWaitCheck);
      return;
    }
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_UPDATE_STOP_SEALUSE);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", id);
    params.put("runId", String.valueOf(runId));
    params.put("dataStatus", "abort");
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), new SimpleReturnResponse(mActivity));
  }

  private void volleyPostDelete(String id) {
    if (TextUtils.isEmpty(id)) return;
    if (!(MyStringUtil.equals(DataStatus.NEW, mItem.getDataStatus()) || MyStringUtil.equals(
        DataStatus.ABORT, mItem.getDataStatus()))) {
      ToastUtil.show(R.string.draftOrAbort);
      return;
    }
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_DELETE_SEALUSE);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", id);
    params.put("deleteFormRecord", String.valueOf(true));
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), new SimpleReturnResponse(mActivity));
  }

  private void volleyPostSave(VolleyResponse response) {
    if (slvApplyText.isEmptyContent()
        || slvSealsType.isEmptyContent()
        || slvUseName.isEmptyContent()) {
      ToastUtil.show(R.string.notComplete);
      return;
    }
    //在流程中更改不需要状态验证.true,--false.,
    if ((!(MyStringUtil.equals(DataStatus.NEW, mItem.getDataStatus()) || MyStringUtil.equals(
        DataStatus.ABORT, mItem.getDataStatus()))) && (!mParams.isEditBackTime())) {
      ToastUtil.show(R.string.draftOrAbort);
      return;
    }
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_UPDATE_SEALUSE);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.putAll(mItem);
    params.put("applyText", slvApplyText.getTextContent());
    MyUtils.showDialogLoading(getActivity());
    mActivity.volleyPost(url, params.getParams(), response);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    if (mParams.isShowMenuConfirm()) MenuUtil.addSubMenu(menu, MENU_ITEM_CONFIRM, R.string.confirm);
    if (mParams.isShowMenuAlter()) MenuUtil.addSubMenu(menu, MENU_ITEM_ALTER, R.string.alter);
    if (mParams.isShowMenuDelete()) MenuUtil.addSubMenu(menu, MENU_ITEM_DELETE, R.string.delete);
    if (mParams.isShowMenuRun()) MenuUtil.addSubMenu(menu, MENU_ITEM_RUN, R.string.runFlow);
    if (mParams.isShowMenuStop()) MenuUtil.addSubMenu(menu, MENU_ITEM_STOP, R.string.stopFlow);
  }

  private void volleyPostInit(String id) {
    if (MyStringUtil.isEmpty(id)) return;
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_QUERY_DETAIL_SEALUSE);
    ParamsNotEmpty params = new ParamsNotEmpty();
    params.put("id", id);
    mActivity.volleyPost(url, params.getParams(), new VolleyResponse() {
      @Override public boolean ifToastError() {
        return false;
      }

      @Override public void onVolleyError(VolleyError arg0) {

      }

      @Override public void onVolleyResponse(String json) throws JSONException {
        BaseOriginal<RSealsUseApp> result =
            new Gson().fromJson(json, new TypeToken<BaseOriginal<RSealsUseApp>>() {
            }.getType());
        bindData(result.getData());
      }
    });
  }

  private void bindData(RSealsUseApp mItem) {
    if (mItem == null) return;
    this.mItem = mItem;
    slvActBackDays.getTvContent().setText(MyDateUtil.format(mItem.getActBackDays()));
    slvActUseDays.getTvContent().setText(MyDateUtil.format(mItem.getActUseDays()));
    slvAgent.getTvContent().setText(mItem.getAgent());
    slvApplydeptDate.getTvContent().setText(MyDateUtil.format(mItem.getApplydeptDate()));
    slvApplydeptName.getTvContent().setText(mItem.getApplydeptName());
    slvApplyNo.getTvContent().setText(mItem.getApplyNo());
    slvApplyText.getTvContent().setText(mItem.getApplyText());
    slvDataStatusName.getTvContent().setText(DataStatus.getDataStatusName(mItem.getDataStatus()));
    slvDocBlob.getTvContent().setText(mItem.getDocBlob());
    clvIsCarryOutName.getCbCheck().setChecked(mItem.isCarryOut());
    slvRegDate.getTvContent().setText(MyDateUtil.format(mItem.getRegDate(), MyDateUtil.TYPE_DATE));
    slvRegStaffName2.getTvContent().setText(mItem.getRegStaffName());
    slvRemark.getTvContent().setText(mItem.getRemark());
    slvSealsType.getTvContent().setText(mItem.getSealsType());
    slvUseName.setTextContent(mItem.getUseName());
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != Activity.RESULT_OK) return;
    if (requestCode == REQUEST_ALTER) {
      mActivity.setResult(Activity.RESULT_OK);
      initData();
      initView(null, null);
    }
    if (requestCode == REQUEST_CHOOSE_FILE) {
      String path = FileUtil.getPath(getActivity(), data.getData());
      if (MyStringUtil.isEmpty(path)) return;
      //上传文件
      showDialog(FileUploadDialgFragment.newInstance(path, mItem.getId(), "imsoa.r_seals_use_app")
          .setCallBack(new FileUploadDialgFragment.CallBack() {
            @Override public void uploadSuccess(String path) {
              if (MyStringUtil.isEmpty(path)) return;
              mItem.setDocPath(path);
              mItem.setDocBlob(FileUtil.getFileNameByFilePath(path));
              slvDocBlob.getTvContent().setText(mItem.getDocBlob());
            }
          }), 0);
    }
  }
}
